package com.lyl.serviceedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyl.commonutils.R;
import com.lyl.exception.ZxjyException;
import com.lyl.serviceedu.cloudclient.VodClient;
import com.lyl.serviceedu.entity.Course;
import com.lyl.serviceedu.entity.CourseDescription;
import com.lyl.serviceedu.entity.vo.CourseApiVo;
import com.lyl.serviceedu.entity.vo.CourseInfoVo;
import com.lyl.serviceedu.entity.vo.CoursePublishVo;
import com.lyl.serviceedu.mapper.CourseMapper;
import com.lyl.serviceedu.query.CourseQuery;
import com.lyl.serviceedu.service.ChapterService;
import com.lyl.serviceedu.service.CourseDescriptionService;
import com.lyl.serviceedu.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.serviceedu.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-06-11
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    //课程描述注入
    @Autowired
    private CourseDescriptionService courseDescriptionService;

    //注入小节和章节service
    @Autowired
    private VideoService eduVideoService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private VodClient vodClient;

    @Override
    public CourseApiVo selectInfoWebById(Long id) {
        this.updatePageViewCount(id);
        return baseMapper.selectInfoWebById(id);
    }

    @Override
    public void updatePageViewCount(Long id) {
        Course course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }


    @Override
    @Transactional
    @CacheEvict(value = "couser",key = "'listIndexCourse'",allEntries = true)
    public boolean updateInfoVo(CourseInfoVo courseInfoVo) {
        Course eduCourse = new Course();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);

        int insert = baseMapper.updateById(eduCourse);
        if(insert == 0) {
            //添加失败
            throw new ZxjyException(20001,"添加课程信息失败");
        }

        //获取添加之后课程id
        Long cid = eduCourse.getId();
        System.out.println("cid:"+ cid);

        //2 向课程简介表添加课程简介
        //edu_course_description
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        courseDescription.setId(cid);

        return  courseDescriptionService.updateById(courseDescription);
    }


    /**
     * 根据讲师id查询当前讲师的课程列表
     * @param teacherId
     * @return
     */
    @Override
    public List<Course> selectByTeacherId(Long teacherId) {

        QueryWrapper<Course> queryWrapper = new QueryWrapper<Course>();

        queryWrapper.eq("teacher_id", teacherId);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");

        List<Course> courses = baseMapper.selectList(queryWrapper);
        return courses;
    }

    @Override
    public void pageQuery(Page<Course> pageParam, CourseQuery courseQuery) {

        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_create");

        if (courseQuery == null){
            baseMapper.selectPage(pageParam, queryWrapper);
            return;
        }

        String title = courseQuery.getTitle();
        String teacherId = courseQuery.getTeacherId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String subjectId = courseQuery.getSubjectId();

        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }

        if (!StringUtils.isEmpty(teacherId) ) {
            queryWrapper.eq("teacher_id", teacherId);
        }

        if (!StringUtils.isEmpty(subjectParentId)) {
            queryWrapper.ge("subject_parent_id", subjectParentId);
        }

        if (!StringUtils.isEmpty(subjectId)) {
            queryWrapper.ge("subject_id", subjectId);
        }

        baseMapper.selectPage(pageParam, queryWrapper);
    }

    //根据课程id查询课程基本信息
    @Override
    public CourseInfoVo getCourseInfo(Long courseId) {
        //1 查询课程表
        Course eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);

        //2 查询描述表
        CourseDescription courseDescription = courseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(courseDescription.getDescription());

        return courseInfoVo;
    }

    //添加课程基本信息的方法
    @Override
    @Transactional
    @CacheEvict(value = "couser",key = "'listIndexCourse'",allEntries = true)
    public Long saveCourseInfo(CourseInfoVo courseInfoVo) {
        //1 向课程表添加课程基本信息
        //CourseInfoVo对象转换eduCourse对象
        Course eduCourse = new Course();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);

        System.out.println("service:" + courseInfoVo);
        System.out.println("eduCourseservice:" + eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if(insert == 0) {
            //添加失败
            throw new ZxjyException(20001,"添加课程信息失败");
        }

        //获取添加之后课程id
        Long cid = eduCourse.getId();
        System.out.println("cid:"+ cid);

        //2 向课程简介表添加课程简介
        //edu_course_description
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        courseDescription.setId(cid);
        courseDescriptionService.save(courseDescription);

        return cid;
    }

    @Override
    public CourseInfoVo getByCourseId(Long id) {
        CourseInfoVo courseInfo= new CourseInfoVo();
        Course course= baseMapper.selectById(id);
        BeanUtils.copyProperties(course,courseInfo);

        CourseDescription courseDescription= courseDescriptionService.getById(id);

        courseInfo.setDescription(courseDescription.getDescription());
        return courseInfo;
    }





    //修改课程信息
    @Override
    @Transactional
    @CacheEvict(value = "couser",key = "'listIndexCourse'",allEntries = true)
 public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //1 修改课程表
        Course eduCourse = new Course();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int update = baseMapper.updateById(eduCourse);
        if(update == 0) {
            throw new ZxjyException(20001,"修改课程信息失败");
        }

        //2 修改描述表
        CourseDescription description = new CourseDescription();
        description.setId(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.updateById(description);
    }

    //根据课程id查询课程确认信息
    @Override
    public CoursePublishVo publishCourseInfo(Long id) {
        //调用mapper
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(id);
        return publishCourseInfo;
    }

    //删除课程
    @Override
    @Transactional
    // 删除了某一个课程 清除缓存
    @CacheEvict(value = "couser",key = "'listIndexCourse'",allEntries = true)
    public boolean removeCourse(Long courseId) {
        System.out.println("删除课程");
        // 课程-描述--> 章节--> 小节--> 视频
        //0.  删除视频
        List<String> vodIds=eduVideoService.getVodIdsByCourseId(courseId);
        if(vodIds.size()>0) {
            //远程调用
            R r = vodClient.removeVideoList(vodIds);
            if(!r.getSuccess()){
                throw new ZxjyException(20001,r.getMessage());
            }
        }
        //1 根据课程id删除小节
        eduVideoService.removeVideoByCourseId(courseId);

        //2 根据课程id删除章节
        chapterService.removeChapterByCourseId(courseId);

        //3 根据课程id删除描述
        courseDescriptionService.removeById(courseId);

        //4 根据课程id删除课程本身
        int result = baseMapper.deleteById(courseId);
        if(result == 0) { //失败返回
            throw new ZxjyException(20001,"删除失败");
        }
        return result>0;
    }

    @Override
    @Cacheable(value = "couser",key = "'listIndexCourse'")
    public List<Course> listIndexCourse() {
        //查询前8条热门课程
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last("limit 16");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> pageListWeb(Page<Course> pageParam, CourseQuery courseQuery) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<Course> records = pageParam.getRecords();
        long current = pageParam.getCurrent();//当前页
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }


}
